package com.smarthome.web.property.controller.statisticsquery;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.smarthome.core.statisticsquery.OrderStatisticsService;
import com.smarthome.domain.bean.ShOrders;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.domain.vo.boss.TimeRange;
import com.smarthome.web.property.utils.UserHolder;

@Controller
@RequestMapping("/orderStatisticsController")
public class OrderStatisticsController {

	@Resource
	private OrderStatisticsService orderStatisticsService;

	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(ShOrders shOrders, PageHelper page,
			TimeRange timeRange) {
		if (timeRange.getStartOrder() != null) {
			shOrders.addQueryData("startGmtCreate",
					timeRange.getStartOrder());
		}
		if (timeRange.getEndOrder() != null) {
			shOrders.addQueryData("endGmtCreate", addDate(timeRange.getEndOrder()));
		}
		if (!UserHolder.isSuperResidence()) {
			shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
		}
		return orderStatisticsService.queryShOrdersPage(shOrders, page);
	}

	@RequestMapping("/getCountAll")
	@ResponseBody
	public Map<String, Object> getCountAll(ShOrders shOrders, TimeRange timeRange) {
		if (timeRange.getStartOrder() != null) {
			shOrders.addQueryData("startGmtCreate",
					timeRange.getStartOrder());
		}
		if (timeRange.getEndOrder() != null) {
			shOrders.addQueryData("endGmtCreate", addDate(timeRange.getEndOrder()));
		}
		if (!UserHolder.isSuperResidence()) {
			shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
		}
		return orderStatisticsService.getCountAll(shOrders);
	}
	
	@RequestMapping("/getPicCount")
	@ResponseBody
	public Map<String, Object> getPicCount() {
		ShOrders shOrders = new ShOrders();
		if (!UserHolder.isSuperResidence()) {
			shOrders.setResidenceId(UserHolder.getCurrentResidenceId());
		}
		return orderStatisticsService.getPicCount(shOrders);
	}
	
	private Date addDate(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(Calendar.DAY_OF_MONTH, 1);
		return cal.getTime();
	}

}
